<template>
  <div>
        <!-- 查询方案 -->
        <a-col :span="24">
            <div class="search-btn-box-gw">
                <div class="item-small" ref="planLi">
                    <ul>
                        <li class="item-plan" :class="planActive == 0?'active':''" @click="changePlane()">所有</li>
                        <li class="item-plan" :title="item.programmeName" :class="item.id == planActive?'active':''" v-for="(item,index) in userSearchList" :key="index" @click="changePlane(item)">{{item.programmeName}}</li>
                        <li class="item-plan" @click="onShowSerch">
                            <!-- <a-icon class="icon-searh-btn" type="file-search" /> 查询 -->
                            自定查询
                            <a-icon class="icon-searh-btn" type="search" />
                        </li>
                    </ul>
                </div>
                <div class="item-small-down" v-if="showDownPlan" @click="showDownPlanFun">
                    <a-icon v-if="iconDirection" type="down" />
                    <a-icon v-else type="up" />
                </div>
            </div>
        </a-col>
        <!-- 查询方案弹窗 -->
        <a-modal class="search-wrapper-box-crm" :visible="visibleSearchPlan" title="查询" @cancel="onHideSerch" width="1000px">
            <div class="content-box">
                <div class="left-box">
                    <a-row class="btn-wrapper">
                        <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                            <div class="btns" @click="planActive != 0?savePlan():''">
                                <a-icon class="btns-icon" type="save" />
                                <div class="btns-text">保存</div>
                            </div>
                        </a-col>
                        <a-col :span="6">
                            <div class="btns" @click="saveAsPlanShow(1)">
                                <a-icon class="btns-icon" type="save" />
                                <div class="btns-text">另存</div>
                            </div>
                        </a-col>
                        <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                            <div class="btns" @click="planActive != 0?saveAsPlanShow(2):''">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">修改</div>
                            </div>
                        </a-col>
                        <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                            <div class="btns" @click="planActive != 0?removePlan({key:planActive}):''">
                                <a-icon class="btns-icon" type="delete" />
                                <div class="btns-text">删除</div>
                            </div>
                        </a-col>
                    </a-row>
                    <div class="plan-list">
                        <ul>
                            <li :class="planActive == 0?'active':''" @click="changePlane()">所有</li>
                            <li v-for="(item,index) in userSearchList" :key="index" :class="item.id == planActive?'active':''" @click="changePlane(item)">{{item.programmeName}}</li>
                        </ul>
                    </div>
                </div>
                <div class="right-box">
                    <a-tabs default-activeKey="1" @change="callback">
                        <a-tab-pane key="1" tab="查询条件">
                            <dynamic-condition v-if="visibleSearchPlan" :checkable="true" :conditions="dataSource" :show="true" :userSearchList="userSearchList"  :changePlane="changePlane" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></dynamic-condition>
                        </a-tab-pane>
                    </a-tabs>
                </div>
            </div>
            <template slot="footer">
                <div>
                    <!-- <div style="float:left">
                        <a-checkbox :checked="planActive == defaultPlanActive?true:false" @change="inPagePlanSave">
                            下次以此方案进入
                        </a-checkbox>
                    </div> -->
                    <a-button type="primary" @click="onSerch">查询</a-button>
                    <a-button @click="onHideSerch" class="margin-left-10">取消</a-button>
                </div>
            </template>
            <a-modal :title="nowPlanType==1?'保存为另一个方案':'修改方案标题'" :visible="saveASVisible" width="400px" centered @cancel="saveAsPlanClose">
                <a-input v-model="saveAsName" placeholder="请输入查询方案名称"></a-input>
                <template slot="footer">
                    <div>
                        <a-button type="primary" @click="saveAsPlanSubmit(1)">确定</a-button>
                        <a-button @click="saveAsPlanClose" class="margin-left-10">取消</a-button>
                    </div>
                </template>
            </a-modal>
        </a-modal>
  </div>
</template>

<script>

import { save, remove, myplan, systemplan } from '@/api/erp/reportProgramme';
import { DynamicCondition } from "@/components/DynamicCondition";
import getDate from "@/utils/tool/date";

export default {
     components: {
        DynamicCondition
    },
    data(){
        return{
            reportCode: null,               //方案编码
            planActive: 0,                  // 选中的方案
            userSearchList: [],             // 查询方案集合
            showDownPlan: false,            // 方案溢出显示
            iconDirection: true,            //图标方向
            visibleSearchPlan: false,       //查询方案弹窗
            orgDataSource:[],       //方案动态数据(原始)    
            dataSource: [],         //方案动态数据
            saveAsName: '',         //另存名称
            saveASVisible: false,   //另存名字弹窗
            nowPlanType: null,      //修改还是另存 //type==1新增，type==2改名
            nowPlanData: [],        //当前显示数据
        }
    },
    created(){

    },
    methods:{
        //初始化 方案
        initCondition(initData){
            let {dataSource,reportCode} = initData;
            Object.assign(this,initData);
            console.log("初始化 方案",this.dataSource);
            this.getMyselfPlan();
        },
        //关闭 方案弹窗
        onHideSerch () {
            this.visibleSearchPlan = false;
        },
        //打开 方案弹窗
        onShowSerch () {
            this.visibleSearchPlan = true;
        },
        /**
         * gw 处理方案过多溢出 2021年8月28日09:11:29
         */
        showDownCheck () {
            //方案 和 外层box 宽度比较
            if (document.getElementsByClassName('item-small').length == 0) {
                //处理和其他页面同时打开,获取不到该bom报错的处理
                return;
            }
            let planWidth = document.getElementsByClassName('item-small')[0].clientWidth;
            let planList = document.getElementsByClassName('item-plan');
            let planListWidthTotal = null;
            planList.forEach(item => {
                // console.log(item.clientWidth)
                planListWidthTotal = planListWidthTotal + item.clientWidth;
            });
            planListWidthTotal = planListWidthTotal + planList.length * 5;

            // console.log('方案总长度：', planListWidthTotal, ',当前显示方案dom的宽度：', planWidth)
            if (planListWidthTotal > planWidth) {
                this.showDownPlan = true;
                this.iconDirection = true;
            } else {
                this.showDownPlan = false;
                this.iconDirection = false;
            }
        },
        /************** 查询方案 接口 **************/
        //获取个人方案列表
        getMyselfPlan () {
            myplan({ reportCode: this.reportCode, businessType: this.businessType ? this.businessType : null }).then((res) => {
                if (res.code == 200) {
                    console.log(res);
                    this.userSearchList = res.data;
                    //保存过后刷新 查询条件和报表设计
                    console.log(this.planActive);
                    if (this.planActive != 0) {
                        this.userSearchList.forEach(plan => {
                            if (plan.id == this.planActive) {
                                this.dataSource = JSON.parse(plan.programmeJson);
                            }
                        });
                    }

                    // //如果当前是新增的另存
                    // if (this.nowPlanType == 1) {
                    //     this.changePlane(this.userSearchList[this.userSearchList.length - 1])
                    // } else if (this.nowPlanType == 2) {
                    //     let _this = this;
                    //     setTimeout(() => {
                    //         let data = this.userSearchList.filter(item => item.id == this.planActive);
                    //         _this.changePlane(data[0]);
                    //     }, 500)
                    // }
                }
            }).catch((e) => {
                // this.$message.error('请求出错', 1)
            })
        },
        //点击自定方案事件
        changePlane (data) {
            if(data){
                this.nowPlanData = data;//当前显示数据
                this.dataSource = JSON.parse(data.programmeJson);
            }else{
                this.dataSource = JSON.parse(JSON.stringify(this.orgDataSource));
            }
            // //处理默认进入方案
            // let planchecked = localStorage.getItem(this.reportCode);
            // if (planchecked) {
            //     this.defaultPlanActive = planchecked;
            // }
            //拖动改变顺序 和 排序
            if (this.dataSource && this.dataSource.length > 0) {
                setTimeout(() => {
                    this.dataSource = [...this.dataSource];
                    this.dataSource.map((item, index) => {
                        item.sort = index + 1;
                    });
                    this.drag();
                }, 500)
            }
            //物料编码开始和结束值
            for (let i = 0; i < this.dataSource.length; i++) {
                let f = this.dataSource[i];
                if ((f.type == "时间" || f.type == "日期") && f.rangDateVal) {
                        let arr = f.rangDateVal;
                        let dateType = arr[0];
                        /***** 重新计算当前时间 *****/
                        let beginDate, endDate;
                        switch (dateType) {
                            case "今日":
                                beginDate = getDate.getToday().starttime;
                                endDate = getDate.getToday().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "昨日":
                                beginDate = getDate.getYesterday().starttime;
                                endDate = getDate.getYesterday().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "本周":
                                beginDate = getDate.getCurrWeekDays().starttime;
                                endDate = getDate.getCurrWeekDays().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "上周":
                                beginDate = getDate.getLastWeekDays().starttime;
                                endDate = getDate.getLastWeekDays().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "本月":
                                beginDate = getDate.getCurrMonthDays().starttime;
                                endDate = getDate.getCurrMonthDays().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "上月":
                                beginDate = getDate.getLastMonthDays().starttime;
                                endDate = getDate.getLastMonthDays().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "本季度":
                                beginDate = getDate.getCurrQuarter().starttime;
                                endDate = getDate.getCurrQuarter().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "上季度":
                                beginDate = getDate.getLastQuarter().starttime;
                                endDate = getDate.getLastQuarter().endtime;
                                arr[1] = [beginDate, endDate]; break;
                        }
                         console.log("conditionBox:查询计算时间",arr);
                        f.rangDateVal = arr;
                    }
                if (f.code == 'inventoryCode') {
                    if (f.rangDateVal != null) {
                        this.beginCode = f.rangDateVal[1][0];
                        this.endCode = f.rangDateVal[1][1];
                    } else {
                        this.beginCode = '';
                        this.endCode = '';
                    }
                }
                if (f.code == 'inventoryId') {
                    if (f.value != null) {
                        this.inventoryId = f.value;
                        this.inventoryName = f.showvalue;
                    } else {
                        this.inventoryId = '';
                        this.inventoryName = '';
                    }
                }
            }
            this.planActive = data?data.id:0;
            this.nowPlanType = null;
            this.activeKey = '1';
            this.onSerch();
        },
        callback (e) {
            this.activeKey = e;
            if (this.dataSource && this.dataSource.length > 0 && e == 2) {
                this.$nextTick(() => {
                    this.drag();
                })
            }
        },
        onSerch(){
            let { dataSource } = this;
            let postData = {};
            dataSource.forEach(item=>{
                if(item.value){
                    postData[item.code] = item.value;
                }else if(item.rangDateVal){
                    if(item.rangDateVal.length > 1){
                        let timeArr = item.rangDateVal[1];
                        if(timeArr.length > 1){
                            postData[item.code+"Start"] = timeArr[0];
                            postData[item.code+"End"] = timeArr[1];
                        }
                    }
                }
            })
            console.log("方案盒子postData：",postData);
            this.$emit("callBack",postData);
        },
        //保存方案
        savePlan (t) {
            let data = this.nowPlanData;
            let requestData = {
                id: data.id,
                programmeName: data.programmeName,//方案名称
                programmeJson: JSON.stringify(this.dataSource),   //方案json
                reportCode: this.reportCode,
                businessType: this.businessType ? this.businessType : null,
            }

            let num = 0;//显示字段
            let summary = 0;//聚合字段
            for (let i = 0; i < this.dataSource.length; i++) {
                if (this.dataSource[i].onShow) {
                    num++;
                }
                if (this.dataSource[i].onSummary) {
                    summary++;
                }
            }
            if (this.componentType == 1) {
                if (num < 3) {
                    this.$message.warning('明细列表必须显示 2 列以上', 1);
                    return;
                }
            }

            if (Number(this.beginCode) > Number(this.endCode)) {
                this.$message.warning('物料编码范围结束值不能小于开始值', 1);
                return;
            }


            //必须选择一个聚合字段
            if (this.componentType == 2) {
                if (summary < 1) {
                    this.$message.warning('请选择聚合字段');
                    return;
                }
            }

            console.log('保存的搜索数据：', this.dataSource);
            save(requestData).then((res) => {
                if (res.code == 200) {
                    this.getMyselfPlan();

                    this.$emit('newPlan');//刷新父组件数据

                    //刷新父组件点击的某个自定义查询
                    this.nowPlanData.programmeJson = requestData.programmeJson;
                    this.$emit('changePlane', this.nowPlanData);


                    if (t != 'close') {
                        this.$message.success('保存成功', 1);
                    }
                    if (t == 'close') {
                        this.onHideSerch();
                    }
                }
            }).catch((e) => {
                // this.$message.error('请求出错', 1)
            })
        },
        //另存方案
        saveAsPlanShow (type) {
            this.nowPlanType = type;
            this.saveASVisible = true;
            this.saveAsName = type == 2 ? this.nowPlanData.programmeName : '';
        },
        //取消另存方案
        saveAsPlanClose () {
            this.saveASVisible = false;
        },
        //确定另存方案
        saveAsPlanSubmit () { //type==1新增，type==2改名
            let type = this.nowPlanType;
            let name = this.saveAsName;
            if (name == null || name == '') {
                this.$message.warning('请输入查询方案名称', 1);
                return;
            } else {
                let requestData = {
                    id: null,
                    programmeName: name,//方案名称
                    programmeJson: JSON.stringify(this.dataSource),   //方案json
                    reportCode: this.reportCode,
                    businessType: this.businessType ? this.businessType : null,
                }

                if (type == 2) {
                    requestData.id = this.planActive
                }

                save(requestData).then((res) => {
                    if (res.code == 200) {
                        if (type == 2) {
                            this.$message.success('自定义方案名称修改成功', 1);
                        } else {
                            this.$message.success('自定义新方案保存成功', 1)

                        }
                        this.getMyselfPlan();
                        this.$emit('newPlan');//刷新父组件数据

                        this.saveASVisible = false;
                        this.saveAsName = '';
                    }
                }).catch((e) => {
                    // this.$message.error('请求出错', 1)
                })
            }
        },
        //删除方案
        removePlan () {
            let _this = this;
            this.$confirm({
                title: "提示",
                content: (
                    <span>
                        是否确认删除{_this.nowPlanData.programmeName}?
                    </span>
                ),
                onOk () {
                    remove({ id: _this.nowPlanData.id }).then((response) => {
                        if (response.code === 200) {
                            _this.$message.success('删除成功');
                            //如果删除的是默认进入的方案
                            // let planchecked = localStorage.getItem(_this.reportCode);
                            // console.log(Number(planchecked) == _this.planActive)
                            // if (Number(planchecked) == _this.planActive) {
                            //     localStorage.setItem(_this.reportCode, 0);
                            // }
                            _this.getMyselfPlan();
                            _this.changePlane();
                        } else {
                            // // _this.$message.warning(response.message);
                        }
                    }).catch((e) => {
                        // _this.$message.error('请求出错', 1)
                    })
                },
                onCancel () { },
            });
        },
         // 拖动
        drag () {
            // 首先获取需要拖拽的dom节点
            const el1 = document.querySelectorAll('.dynamic-table-design .ant-table-tbody')[0];
            if (!el1) return false;
            // this.isDrag = true;
            Sortable.create(el1, {
                disabled: false, // 是否开启拖拽
                ghostClass: 'sortable-ghost', //拖拽样式
                animation: 150, // 拖拽延时，效果更好看
                group: { // 是否开启跨表拖拽
                    pull: false,
                    put: false
                },
                onEnd: (e) => { // 这里主要进行数据的处理，拖拽实际并不会改变绑定数据的顺序，这里需要自己做数据的顺序更改
                    let arr = this.dataSource; // 获取表数据

                    let removeItem = arr.splice(e.oldIndex, 1)[0];

                    arr.splice(e.newIndex, 0, removeItem); // 数据处理
                    //提前 赋值一个带值的数组（BUG 修复）
                    this.dataSource = [{}];
                    this.$nextTick(function () {
                        this.dataSource = [...arr];
                        this.dataSource.map((item, index) => {
                            item.sort = index + 1;
                        });
                    });
                }
            });
        },
    }

}
</script>

<style lang="less" scoped>
 .search-btn-box-gw {
    display: flex;
    border-bottom: 1px solid #CCC;
    margin-top: 4px;
    // height: 40px;
    padding-left: 0px;
    width: 100%;

    .item-big {
      flex: 0 0 60px;
      font-size: 14px;
      text-align: center;
      color: #000;
      // font-weight: bold;
      line-height: 20px;
      cursor: pointer;

      .icon-searh {
        font-size: 19px;
        color: rgb(45, 144, 236);
      }
    }

    .item-small-down {
      width: 42px;
      height: 42px;
      line-height: 42px;
      text-align: center;
      cursor: pointer;
    }

    .item-small {
      width: calc(100% - 50px);
      height: 40px;

      ul {
        width: 100%;
        list-style: none;
        padding: 0;
        margin: 0;
        clear: both;
      }

      ul>li {
        float: left;
        // border: 1px solid rgb(162, 187, 203);
        color: #333;
        height: 32px;
        line-height: 32px;
        padding: 0px 10px;
        font-size: 14px;
        // margin-right: 10px;
        max-width: 110px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin-right: 5px;
        margin-top: 7px;
      }

      ul>li.active {
        background: #1E9FFF;
        color: #FFFFFF;
      }

      .icon-searh-btn {
        color: #1e9fff;
      }

      ul>li:hover {
        background: #1E9FFF;
        color: #FFFFFF;

        .icon-searh-btn {
          color: #FFFFFF;
        }
      }

      .item-plan {
        cursor: pointer;
      }
    }
  }
</style>